<?php

namespace MoChat\App\Sales\Service;

use MoChat\App\Sales\Contract\WorkEmployeeContract;
use MoChat\App\Sales\Model\SalesClientTask;
use MoChat\App\Sales\Model\SalesTaskEmployee;
use MoChat\App\Sales\Model\WorkEmployee;
use MoChat\Framework\Service\AbstractService;
use MoChat\App\WorkEmployee\Logic\IndexLogic;

class WorkEmployeeService extends AbstractService implements WorkEmployeeContract
{
    /**
     * @var WorkEmployee
     */
    protected $model;

    public function getSelect($name,$workDepartmentId,$type,$id): array
    {
        $employeeId=(new IndexLogic())->getDepartmentEmployeeIds((int)($workDepartmentId?$workDepartmentId:1));
        $list = $this->model->when(!empty($name), function ($query) use ($name) {
            $query->where('name', 'like', '%' . $name . '%');
        })->when(!empty($employeeId),function ($query)  use ($employeeId){
            $query->whereIn('id',$employeeId);
        })->select([
            'id',
            'name'
        ])->get();
        $list= empty($list) ? [] : $list->toArray();
        if (!empty($list) && $type){
            $ids=array_column($list,'id');
            $employeeIds=[];
            switch ($type){
                //销售任务
                case 1:
                    $employeeIds=SalesTaskEmployee::whereIn('work_employee_id',$ids)
                        ->where('sales_task_id',$id)
                        ->pluck('id','work_employee_id')->toArray();
                    break;
                    //客户开发数
                case 2:
                    $employeeIds=SalesClientTask::whereIn('work_employee_id',$ids)
                        ->where('sales_task_id',$id)
                        ->pluck('id','work_employee_id')->toArray();
                    break;
                default:
            }
            foreach ($list as &$value){
                $value['hasTask']=isset($employeeIds[$value['id']]);
            }
            unset($value);
        }
        return  $list;
    }

    public function getAllWorkEmployeeByIds($ids)
    {
        return $this->model->getAllById($ids);
    }

    public function getDetail($id, $filed = ['*'])
    {
        return $this->model->getOneById($id, $filed);
    }

    /**
     * @param $corpId
     */
    public function getCountByCorpId($corpId)
    {
       $this->model->where('corp_id',$corpId)->count();
    }
}
